package com.bzsg.rightsManagementSystem.config.security_config

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.SecurityMetadataSource
import org.springframework.security.access.intercept.AbstractSecurityInterceptor

import org.springframework.security.web.FilterInvocation
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import java.io.IOException
import javax.servlet.*

@Service
class CustomizeAbstractSecurityInterceptor : AbstractSecurityInterceptor(), Filter {

    @Autowired
    private lateinit var securityMetadataSource: FilterInvocationSecurityMetadataSource

    @Autowired
    fun setMyAccessDecisionManager(accessDecisionManager: CustomizeAccessDecisionManager?) {
        super.setAccessDecisionManager(accessDecisionManager)
    }


    override fun getSecureObjectClass(): Class<*> {
        return FilterInvocation::class.java
    }

    override fun obtainSecurityMetadataSource(): SecurityMetadataSource? {
        return securityMetadataSource
    }

    @Throws(IOException::class, ServletException::class)
    override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
        val fi = FilterInvocation(servletRequest, servletResponse, filterChain)
        invoke(fi)
    }

    @Throws(IOException::class, ServletException::class)
    operator fun invoke(fi: FilterInvocation) {
        //fi里面有一个被拦截的url
        //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
        //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够
        val token = super.beforeInvocation(fi)
        try {
            //执行下一个拦截器
            fi.chain.doFilter(fi.request, fi.response)
        } finally {
            super.afterInvocation(token, null)
        }
    }
}